<template>
  <div class="orderRecordCmpt">
    <div class="form-baseinfo">
      <el-row style="padding-left: 5px; padding-bottom: 10px">
        <el-col :span="12">
          <div>
            <el-input v-model="queryModel" placeholder="输入关键字进行过滤" />
          </div>
        </el-col>
        <el-col :span="2" style="padding-left: 10px">
          <el-button style="width: 100%" size="medium" type="primary" @click="queryProduct">搜索</el-button>
        </el-col>
        <el-col :span="2" style="padding-left: 10px">
          <el-button style="width: 100%" size="medium" type="info" @click="resetting">重置</el-button>
        </el-col>
        <!-- <el-col :span="2" style="padding-left:5px;">
          <el-button size="medium" type="primary" @click="serial">选择扫码枪串口</el-button>
        </el-col> -->
        <el-col :span="4" style="padding-left: 10px">
          <el-button style="width: 100%" size="medium" type="primary" @click="dialogVisible = true"
            >刷卡器设备号</el-button
          >
        </el-col>
        <el-col :span="4" style="padding-left: 10px">
          <el-button style="width: 100%" size="medium" type="primary" @click="exportCategory">导出商品二维码</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <!-- <el-card class="box-card"> -->
          <div style="padding-left: 5px; padding-right: 5px; padding-bottom: 10px">
            <el-tree
              ref="tree"
              class="filter-tree"
              :data="data"
              :props="defaultProps"
              :default-expand-all="defaultExpandAll"
              node-key="id"
              :default-expanded-keys="treeArr"
              @node-click="handleCheckChange"
            />
          </div>
          <!-- </el-card> -->
        </el-col>
        <el-col :span="11">
          <div
            v-infinite-scroll="loadProductCard"
            class="productCardList"
            infinite-scroll-immediate="false"
            :infinite-scroll-disabled="disabled"
            infinite-scroll-distance="20"
          >
            <div v-if="list.length > 0">
              <div v-for="item in list" :key="item.id" class="productCard" lazy>
                <el-card class="card-box">
                  <div slot="header" class="clearfix">
                    <span>{{ item.cName }}</span>
                  </div>
                  <el-row>
                    <el-col :span="7">
                      <div v-if="item.imagesList && item.imagesList.length > 0">
                        <div v-if="item.imagesList[0].imgesUrl == null" class="cardLeft">
                          <img src="@/assets/images/imgError.jpg" class="image" />
                        </div>
                        <div v-else>
                          <img :src="item.imagesList[0].imgesUrl" class="image" />
                        </div>
                      </div>
                      <div v-else class="cardLeft">
                        <img src="@/assets/images/imgError.jpg" class="image" />
                      </div>
                    </el-col>
                    <el-col :span="17">
                      <div v-for="product in item.productList" :key="product.id">
                        <el-button
                          :disabled="product.plbQuantity == 0 ? true : false"
                          class="cardButton"
                          size="medium"
                          @click="insertData(product)"
                          >{{ product.pTitle }}</el-button
                        >
                      </div>
                    </el-col>
                  </el-row>
                </el-card>
              </div>
              <div class="noMore">
                <p v-if="noMore">没有更多了</p>
              </div>
            </div>
            <div v-else class="noMore">
              <p>未查询到搜索结果</p>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>购物车</span>
            </div>
            <div class="shoppingCard">
              <div v-for="(item, index) in shoppingData" :key="index">
                <el-row>
                  <el-col :span="3">
                    <div class="shopping_danger">
                      <el-button type="danger" size="mini" circle @click="deleteByIdShoppingData(item)">
                        <i class="el-icon-delete" />
                      </el-button>
                    </div>
                  </el-col>
                  <el-col :span="21">
                    <div class="shopping_Title">
                      {{ item.pTitle }}
                    </div>
                  </el-col>
                </el-row>
                <el-row class="shopping_specs">
                  <el-col :span="8">
                    <div class="shopping_Tnum">数量：</div>
                  </el-col>
                  <el-col :span="11">
                    <div class="shopping_number">
                      <el-input-number
                        :key="index"
                        v-model="item.quantity"
                        style="width: 100px"
                        :max="99"
                        :min="1"
                        size="mini"
                        :precision="0"
                        @change="quantityChange"
                      />
                    </div>
                  </el-col>
                </el-row>
                <el-row style="margin-top: 10px">
                  <el-col :span="16">
                    <div>￥{{ item.pPrice }}</div>
                  </el-col>
                  <el-col :span="8">
                    <div style="float: right">￥{{ Math.round(item.pPrice * item.quantity * 100) / 100 }}</div>
                  </el-col>
                </el-row>
                <el-divider />
              </div>
              <div v-if="shoppingData.length > 0">
                <el-row style="margin-top: 10px">
                  <el-col :span="16">
                    <div>合计数量：</div>
                  </el-col>
                  <el-col :span="8">
                    <div style="float: right">{{ totalQuantity }}</div>
                  </el-col>
                </el-row>
                <el-row style="margin-top: 10px">
                  <el-col :span="16">
                    <div>合计金额：</div>
                  </el-col>
                  <el-col :span="8">
                    <div style="float: right">￥{{ Math.round(totalAmount * 100) / 100 }}</div>
                  </el-col>
                </el-row>
                <!-- <el-row style="margin-top: 10px; margin-bottom: 10px;">
                  <el-col :span="24">
                    <span>结算方式：</span>
                    <el-radio v-model="payType" label="0">优惠券结算</el-radio>
                    <el-radio v-model="payType" label="1">卡结算</el-radio>
                  </el-col>
                </el-row> -->
                <el-row>
                  <!-- <el-col :span="8" style="padding-right: 7px;">
                    <el-button style="margin-top: 5px;width: 100%;" size="small" type="info"
                      @click="temporarySave">临时保存</el-button>
                  </el-col> -->
                  <el-col :span="12" style="padding-right: 7px; margin-left: 50px">
                    <el-button style="margin-top: 5px; width: 100%" size="small" type="primary" @click="save"
                      >去结算</el-button
                    >
                  </el-col>
                  <el-col :span="6" style="padding-right: 7px">
                    <el-button style="margin-top: 5px; width: 100%" size="small " @click="emptyShoppingData"
                      >清空</el-button
                    >
                  </el-col>
                </el-row>
              </div>
              <div v-else-if="shoppingData.length == 0" class="noMore">
                <p>暂无待结算物料</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      title="刷卡器设备号"
      :show-close="false"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-form ref="equipmentNumber" :model="equipment" :rules="rules">
        <el-form-item prop="equipmentNumber">
          <el-input v-model="equipment.equipmentNumber" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveEquipmentNumber('equipmentNumber')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class="settleDialog"
      title="结算信息"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="settleVisb"
      width="40%"
      :before-close="settleclose"
    >
      <el-form ref="settleDialog" :inline="true" label-width="110px" :rules="rules" :model="settleDialog">
        <div v-if="settleData.settleState === 'success'" style="margin-top: 5px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="员工工号：" />
            </el-col>
            <el-col :span="12">
              <span>{{ settleData.userJobNum }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="员工姓名：" />
            </el-col>
            <el-col :span="12">
              <span>{{ settleData.userName }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="员工卡号：" />
            </el-col>
            <el-col :span="12">
              <span>{{ settleData.userCardNo }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属部门：" />
            </el-col>
            <el-col :span="12">
              <span>{{ settleData.departmentName }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属岗位：" />
            </el-col>
            <el-col :span="12">
              <span>{{ settleData.jobName }}</span>
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="获取卡状态：" />
          </el-col>
          <el-col :span="12">
            <div v-if="settleData.settleState === 'loading'">
              <i style="font-size: 20px" class="el-icon-loading" />
              <span style="font-size: 16px">获取卡信息中，请稍后</span>
            </div>
            <el-link
              v-else-if="settleData.settleState === 'success'"
              style="font-size: 16px"
              type="success"
              icon="el-icon-success"
              >获取成功</el-link
            >
            <el-link v-else style="font-size: 16px" type="danger" icon="el-icon-error">获取卡信息失败</el-link>
          </el-col>
        </el-row>
        <el-row v-if="settleData.settleState === 'success' && payType == '0'">
          <el-col :span="8">
            <span style="font-weight: 600; font-size: 14px">优惠券信息状态：</span>
          </el-col>
          <el-col v-if="isCoupon" :span="12">
            <el-link v-if="tableData.length > 0" style="font-size: 16px" type="danger" icon="el-icon-error"
              >可使用优惠券不足</el-link
            >
            <el-link v-else style="font-size: 16px" type="danger" icon="el-icon-error">未找到优惠券信息</el-link>
          </el-col>
          <el-col v-else :span="12">
            <el-link v-if="tableData.length > 0" style="font-size: 16px" type="success" icon="el-icon-success"
              >可结算</el-link
            >
          </el-col>

          <div>
            <el-col style="margin-top: 15px; padding-left: 42px" :span="8">
              <span style="font-weight: 600; font-size: 14px">抵扣情况：</span>
            </el-col>
            <el-col v-if="tableData.length > 0" style="margin-top: 5px; margin-bottom: 5px" :span="12">
              <div v-for="(item, index) in couponUsage" :key="index" style="padding-top: 5px">
                <div v-if="item != ''">{{ item }}</div>
              </div>
            </el-col>
          </div>
          <LPTablePage
            :show-page="false"
            :show-index="false"
            :show-indexfixed="false"
            index-label="顺序"
            style="margin-top: 60px"
            :table-data="tableData"
            :table-column="tableColumn"
            :total="total"
            :current-page="currentPage"
            align="center"
          />
        </el-row>
        <el-row v-if="settleData.settleState === 'success' && payType == '1'">
          <div>
            <el-col :span="8">
              <el-form-item label="卡余额：" />
            </el-col>
            <el-col :span="12">
              <span>￥{{ settleData.settlementMoney }}</span>
            </el-col>
          </div>
        </el-row>
        <el-row v-if="settleData.settleState === 'success' && payType == '1'">
          <div>
            <el-col :span="8">
              <el-form-item label="待支付金额：" />
            </el-col>
            <el-col :span="12">
              <span style="color: red">￥{{ Math.round(totalAmount * 100) / 100 }}</span>
            </el-col>
          </div>
        </el-row>

        <el-row v-if="settleData.settleState === 'error'">
          <el-col :span="8">
            <el-form-item label="失败原因：" />
          </el-col>
          <el-col :span="12">
            <span>{{ settleData.message }}</span>
          </el-col>
        </el-row>
        <el-row
          v-if="settleData.settleState === 'error' || settleData.settleState === 'loading'"
          class="settleSuserCardNo"
        >
          <el-col :span="8">
            <el-form-item label="员工卡号/工号：" />
          </el-col>
          <el-col :span="12">
            <el-form-item prop="userCardNo">
              <el-input v-model="settleDialog.userCardNo" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="settleData.settleState === 'error' || settleData.settleState === 'loading'"
          type="primary"
          @click="getCardDataAgainButton"
          >重新获取</el-button
        >
        <el-button
          v-else-if="settleData.settleState === 'success' && !isCoupon"
          :disabled="settleData.settlementMoney < totalAmount"
          :type="settleData.settlementMoney < totalAmount ? 'info' : 'primary'"
          @click="settleOrderSave"
          >结 算</el-button
        >
        <el-button
          v-if="settleData.settleState === 'error' || settleData.settleState === 'loading'"
          type="primary"
          @click="manualSettle('settleDialog')"
          >手动获取</el-button
        >
        <el-button type="info" @click="settleclose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTreeCategoryInfo } from '@/api/LaborProtection/categoryInfo'
import {
  getQueryProductList,
  insertAndupdateOrder,
  settleByIdOrder,
  getCardData,
  getCouponByUser,
  getByCardEmployee,
  getBalance
} from '@/api/LaborProtection/order'
import { exportGetImgExcel } from '@/api/LaborProtection/export'
import { download, parseTime } from '@/utils/lpUtils'
import data from '../../pdf/index.vue'
import LPTablePage from '@/components/LPTablePage/index.vue'
import signaR from './signalR.js'

export default {
  name: 'OrderRecordCmpt',
  components: { LPTablePage },
  // watch: {
  //   filterText(val) {
  //     this.$refs.tree.filter(val);
  //   }
  // },
  data() {
    return {
      // userPngUrl: 'http://file.dev.oranllc.com:8080/api/file-management/files/www/new/3a0a580d7327fb88b36fc92b85ccb917.png',
      queryModel: '',
      filterText: '',
      QCategoryNo: '',
      checkName: '',
      code: '',
      keyCode: '',
      NewTime: '',
      TimingTime: '',
      orderId: '',
      total: 0,
      currentPage: 1,
      pageSize: 10,
      totalQuantity: 0,
      totalAmount: 0,
      inventoryType: 0,
      defaultExpandAll: false,
      noMore: false,
      dialogVisible: false,
      settleVisb: false,
      data: [],
      treeArr: [],
      list: [],
      shoppingData: [],
      equipment: {
        equipmentNumber: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      settleData: {
        departmentName: '',
        userName: '',
        settlementMoney: 0,
        userCardNo: '',
        userJobNum: '',
        jobName: '',
        message: '',
        settleState: ''
      },
      settleDialog: {
        userCardNo: ''
      },
      payType: '1',
      tableData: [],
      // 表格字段
      tableColumn: [
        { label: '优惠券名称', prop: 'couponName' },
        { label: '发放记录编号', prop: 'couponRecordId' },
        { label: '优惠券有效期起', prop: 'startTime' },
        { label: '优惠券有效期止', prop: 'endTime' },
        { label: '优惠券内容', prop: 'materialName' }
      ],
      rules: {
        equipmentNumber: [{ required: true, message: '请输入设备号', trigger: 'blur' }],
        userCardNo: [{ required: true, message: '请输入卡号', trigger: 'blur' }]
      },
      materialList: [],
      isCoupon: false,
      couponUsage: [],
      signaR: signaR
    }
  },

  computed: {
    disabled() {
      return this.loading
    }
  },
  mounted() {
    this.signaR.initSR()
    // 判断他有没有输入过设备号。没有的话就要让他先输入设备号
    if (localStorage.getItem('equipmentNumber') != null) {
      this.equipment.equipmentNumber = localStorage.getItem('equipmentNumber')
    } else {
      this.dialogVisible = true
    }
    this.getTreeCategoryInfo()
    this.getQueryProductList()
    this.signalR_on_ReceiveMessage()
    // 监听扫码，2.4G模式
    window.document.onkeypress = (e) => {
      // console.log("监听扫码", window.event);
      if (window.event) {
        // IE
        this.keyCode = e.keyCode
      } else if (e.which) {
        // Netscape/Firefox/Opera
        this.keyCode = e.which
      }
      // console.log("keyCode", keyCode)
      if (this.keyCode === 13) {
        if (this.code.length < 3) return // 手动输入的时间不会让code的长度大于2，这里只会对扫码枪有
        this.queryModel = this.code
        this.QCategoryNo = ''
        this.getQueryProductList()
        this.code = ''
        return
      }
      this.code += e.key
    }
  },
  methods: {
    // //监听扫码，串口模式
    // 选择串口
    async serial() {
      // 浏览器支持serial
      if ('serial' in navigator) {
        console.log('当前浏览器支持serial')
        const port = await navigator.serial.requestPort()
        await port.open({ baudRate: 9600 })
        console.log('port的内容是：', port)
        const reader = port.readable.getReader()
        try {
          this.textV = '串口模式扫码枪输入的内容:'
          while (true) {
            const { value, done } = await reader.read()
            if (done) {
              reader.releaseLock()
              break
            }
            console.log('测试value的内容是', value)
            var text = this.Uint8ArrayToString(value)
            console.log('解码内容：', text)
            this.textV = '串口模式扫码枪输入的内容:' + text
            this.queryModel = text
            this.QCategoryNo = ''
            this.getQueryProductList()
          }
        } catch (error) {
          console.error(error)
        } finally {
          reader.releaseLock()
          console.log('允许稍后关闭串口。')
          await readableStreamClosed.catch(() => {
            /* Ignore the error */
          })
          await port.close()
        }
      }
    },
    // 解析串口数据
    Uint8ArrayToString(serialData) {
      var out, i, len, c
      var char2, char3
      out = ''
      len = serialData.length
      i = 0
      while (i < len) {
        c = serialData[i++]
        switch (c >> 4) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            // 0xxxxxxx
            out += String.fromCharCode(c)
            break
          case 12:
          case 13:
            // 110x xxxx   10xx xxxx
            char2 = serialData[i++]
            out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f))
            break
          case 14:
            // 1110 xxxx  10xx xxxx  10xx xxxx
            char2 = serialData[i++]
            char3 = serialData[i++]
            out += String.fromCharCode(((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0))
            break
        }
      }
      return out
    },
    saveEquipmentNumber(equipmentNumber) {
      this.$refs[equipmentNumber].validate((valid) => {
        if (valid) {
          localStorage.setItem('equipmentNumber', this.equipment.equipmentNumber)
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    loadProductCard() {
      this.loading = true
      setTimeout(() => {
        if (this.total < this.pageSize + 10) {
          this.pageSize = this.total
        } else {
          this.pageSize = this.pageSize + 10
        }
        if (this.noMore) {
          return
        }
        this.getQueryProductList()
        if (this.total == this.pageSize) {
          this.noMore = true
        }
      }, 1000)
    },
    deleteByIdShoppingData(data) {
      this.$confirm('是否删除该条数据', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          const tempList = []
          this.shoppingData.forEach((item) => {
            if (item.id != data.id) {
              tempList.push(item)
            }
          })
          this.shoppingData = tempList
          this.getShoppingDataTotal()
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('已取消该操作')
        })
    },

    getShoppingDataTotal() {
      this.totalQuantity = 0
      this.totalAmount = 0
      this.shoppingData.forEach((item) => {
        this.totalQuantity = this.totalQuantity + item.quantity
        this.totalAmount = this.totalAmount + Math.round(item.quantity * item.pPrice * 100) / 100
      })
    },
    quantityChange() {
      this.getShoppingDataTotal()
    },
    insertData(product) {
      const flag = this.shoppingData.some((item) => item.id == product.id)
      if (flag) {
        this.shoppingData.forEach((item) => {
          if (item.id == product.id) {
            if (item.quantity < 99) {
              item.quantity = item.quantity + 1
            } else {
              return this.$message.error('单个商品最高可购 99 件')
            }
          }
        })
      } else {
        this.shoppingData.push({
          ...product,
          quantity: 1
        })
      }
      console.log(product)
      this.getShoppingDataTotal()
    },
    resetting() {
      this.queryModel = ''
      this.checkName = ''
      this.currentPage = 1
      this.pageSize = 10
      this.QCategoryNo = ''
      this.getQueryProductList()
    },
    emptyShoppingData() {
      this.$confirm('是否清空购物车', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.$message.success('清空成功')
          this.shoppingData = []
          this.getShoppingDataTotal()
        })
        .catch(() => {
          this.$message.info('已取消该操作')
        })
    },
    getNewOptions(maps) {
      const that = this
      return maps.map((item) => {
        return {
          label: item.cName,
          id: item.id,
          categoryNo: item.categoryNo,
          children: item.childList ? that.getNewOptions(item.childList) : item.childList
        }
      })
    },
    settleOrderSave() {
      const ordersProducts = this.getOrderProducts()
      const params = {
        userCardNo: this.settleData.userCardNo,
        userJobNum: this.settleData.userJobNum,
        departmentName: this.settleData.departmentName,
        userName: this.settleData.realName,
        jobName: this.settleData.jobName,
        status: 1,
        inventoryType: this.inventoryType,
        payType: this.payType,
        EquipmentNO: this.equipment.equipmentNumber
      }

      ordersProducts.forEach((item) => {
        item.userCardNo = this.settleData.userCardNo
        item.userJobNum = this.settleData.userJobNum
        item.departmentName = this.settleData.departmentName
        item.userName = this.settleData.realName
        item.jobName = this.settleData.jobName
      })

      params.ordersProducts = ordersProducts
      insertAndupdateOrder(params)
        .then((res) => {
          this.orderId = res.id
          const settleDate = {
            id: this.orderId,
            userCardNo: this.settleData.userCardNo
          }
          settleByIdOrder(settleDate)
            .then((settle) => {
              this.$message.success('订单结算成功')
              this.settleSave()
              this.shoppingData = []
            })
            .catch((err) => {
              return this.$message.error(err.response.data.error.message)
            })
        })
        .catch((err) => {
          return this.$message.error(err.response.data.error.message)
        })
    },
    getTreeCategoryInfo() {
      const data = {}
      getTreeCategoryInfo(data).then((res) => {
        this.data = this.getNewOptions(res.items)
        res.items.forEach((item) => {
          this.treeArr.push(item.id)
        })
      })
    },
    handleCheckChange(data) {
      this.QCategoryNo = data.categoryNo
      this.queryModel = ''
      this.checkName = data.label
      this.pageSize = 10
      this.getQueryProductList()
    },
    queryProduct() {
      this.currentPage = 1
      this.pageSize = 10
      this.getQueryProductList()
    },
    getOrderProducts() {
      const ordersProducts = []
      this.shoppingData.forEach((item) => {
        ordersProducts.push({
          pNo: item.pNo,
          pCount: item.quantity
        })
        this.materialList.push({
          materialName: item.pTitle,
          materialCode: item.pNo,
          materialCodeNumber: item.quantity,
          qCategoryNo: item.qCategoryNo
        })
      })
      return ordersProducts
    },
    temporarySave() {
      if (this.stockJudge()) {
        return
      }
      const ordersProducts = this.getOrderProducts()

      const params = {
        EquipmentNO: this.equipment.equipmentNumber,
        status: 0,
        inventoryType: this.inventoryType,
        ordersProducts: ordersProducts
      }
      insertAndupdateOrder(params)
        .then((res) => {
          if (!res.error) {
            this.resetting()
            this.shoppingData = []
            this.$message.success('订单保存成功，请在【收银订单】继续结算')
          }
        })
        .catch((err) => {
          return this.$message.error(err.response.data.error.message)
        })
    },
    signalR_on_ReceiveMessage() {
      this.signaR.SR.on('ReceiveCard', (state, message, cardNo, card) => {
        console.log(state, message, cardNo, card)
        if (state == 1) {
          this.settleData.settleState = 'error'
          this.settleData.message = message
          return
        }
        if (card == '') return
        if (this.materialList.length == 0) return
        if (cardNo != this.equipment.equipmentNumber) return
        const params = {
          cardNo: card
        }
        getByCardEmployee(params).then((res) => {
          this.settleVisb = true
          this.settleData.settleState = 'success'
          this.settleData.message = ''
          this.settleData.jobName = res.jobName
          this.settleData.departmentName = res.departmentName
          this.settleData.userName = res.realName
          this.settleData.userCardNo = res.cardNo
          this.settleData.userJobNum = res.jobNum
          // this.settleData.settlementMoney = res.settlementMoney;

          this.$nextTick(() => {
            if (this.payType == '0') {
              const data = {
                userNo: res.jobNum,
                material: this.materialList
              }
              getCouponByUser(data).then((res1) => {
                this.settleData.settleState = 'success'
                this.settleVisb = true
                if (this.payType == '0') {
                  if (!res1.mark) {
                    // this.isCoupon = true;
                    if (res1.orderCouponItemDtos.length > 0) {
                      this.couponUsage = res1.topic.split(';')
                    }
                  } else {
                    const tempList = []
                    this.materialList.forEach((tempItem) => {
                      tempList.push(
                        `${tempItem.materialName}:购买数量:${tempItem.materialCodeNumber},优惠券抵扣数量:${tempItem.materialCodeNumber}`
                      )
                    })
                    this.couponUsage = tempList
                  }
                }
                this.tableData = res1.orderCouponItemDtos
              })
            } else {
              const data = {
                custId: res.custId,
                custThirdId: ''
              }
              getBalance(data).then((res1) => {
                this.settleData.settlementMoney = Math.round(res1.accBal) / 100
              })
            }
          })
        })
      })
    },
    save() {
      if (this.stockJudge()) {
        return
      }
      if (localStorage.getItem('warehouseType') == null) {
        this.inventoryType = 0
      } else {
        this.inventoryType = 1
      }
      this.getOrderProducts()
      this.signaR.SR.invoke('GetCard', this.equipment.equipmentNumber)
      // let temp = new Date();
      // this.TimingTime = new Date();
      // this.settleTime = parseTime(temp);
      // this.signalR_on_ReceiveMessage();
      this.settleData.settleState = 'loading'
      this.settleVisb = true
    },
    getCardDataAgainButton() {
      // this.settleDialog = {
      //   userCardNo: '',
      // }
      // this.settleData.settleState = 'loading'
      // //每次点击重新结算按钮时，去拿点击的时间
      // this.TimingTime = new Date();
      // this.getCardDataAgain(this.TimingTime);
      this.signaR.SR.invoke('GetCard', this.equipment.equipmentNumber)
    },
    getCardDataAgain(Timing) {
      const data = {
        deviceNo: this.equipment.equipmentNumber
      }
      getCardData(data).then((cardData) => {
        if (parseTime(cardData.data.rT_BODY.xfrqsj) > this.settleTime) {
          const settleDate = {
            id: this.orderId
          }
          settleByIdOrder(settleDate)
            .then((settle) => {
              this.settleData.message = ''
              this.settleData.jobName = settle.data.jobName
              this.settleData.userName = settle.data.userName
              this.settleData.userCardNo = settle.data.userCardNo
              this.settleData.userJobNum = settle.data.userJobNum
              // this.settleData.settlementMoney = settle.data.settlementMoney;
              this.settleData.settleState = 'success'
            })
            .catch((err) => {
              this.settleData.message = err.response.data.error.message
              this.settleData.settleState = 'error'
            })
        } else {
          const NewTime = new Date()
          const tempSettleTime = new Date(Timing).setMinutes(new Date(Timing).getMinutes() + 1)
          if (parseTime(NewTime) > parseTime(tempSettleTime)) {
            this.settleData.message = '获取支付信息超时'
            return
          } else {
            setTimeout(() => {
              this.getCardDataAgain(this.TimingTime)
            }, 1000)
          }
        }
      })
    },
    handleClose() {},
    manualSettle(settleDialog) {
      this.$refs[settleDialog].validate((valid) => {
        if (valid) {
          const params = {
            cardNo: this.settleDialog.userCardNo
          }
          this.settleData.settleState = 'success'
          getByCardEmployee(params).then((res) => {
            if (res.cardNo == null) {
              this.settleData.message = '卡号或工号不存在'
              this.settleData.settleState = 'error'
              return
            }
            this.settleVisb = true
            this.settleData.settleState = 'success'
            this.settleData.message = ''
            this.settleData.jobName = res.jobName
            this.settleData.departmentName = res.departmentName
            this.settleData.userName = res.realName
            this.settleData.userCardNo = res.cardNo
            this.settleData.userJobNum = res.jobNum

            this.$nextTick(() => {
              if (this.payType == '0') {
                const data = {
                  userNo: res.jobNum,
                  material: this.materialList
                }
                getCouponByUser(data).then((res1) => {
                  this.settleData.settleState = 'success'
                  this.settleVisb = true
                  if (!res1.mark) {
                    this.isCoupon = true
                    if (res1.orderCouponItemDtos.length > 0) {
                      this.couponUsage = res1.topic.split(';')
                    }
                  } else {
                    const tempList = []
                    this.materialList.forEach((tempItem) => {
                      tempList.push(
                        `${tempItem.materialName}:购买数量:${tempItem.materialCodeNumber},优惠券抵扣数量:${tempItem.materialCodeNumber}`
                      )
                    })
                    this.couponUsage = tempList
                  }
                  this.tableData = res1.orderCouponItemDtos
                })
              } else {
                const data = {
                  custId: res.custId,
                  custThirdId: ''
                }
                getBalance(data).then((res1) => {
                  this.settleData.settlementMoney = Math.round(res1.accBal) / 100
                })
              }
            })
          })
        }
      })
    },
    settleclose() {
      if (localStorage.getItem('warehouseType') == null) {
        this.inventoryType = 0
      } else {
        this.inventoryType = 1
      }
      this.$confirm('是否退出结算', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        this.settleSave()
      })
    },
    settleSave() {
      this.settleVisb = false
      this.$nextTick(() => {
        // 虽然写的是Save 实际上就是确认后初始化数据的操作
        this.settleData = {
          userName: '',
          settlementMoney: '',
          userCardNo: '',
          userJobNum: '',
          jobName: '',
          message: '',
          settleState: ''
        }
        this.settleDialog = {
          userCardNo: ''
        }
        this.TimingTime = ''

        this.materialList = []
        this.isCoupon = false
        this.couponUsage = []
      })
    },
    exportCategory() {
      const params = {
        CCLass: 2
      }
      exportGetImgExcel(params).then((res) => {
        console.log(res)
        download(res, '商品条形码')
      })
    },
    stockJudge() {
      const confirmText = []
      this.shoppingData.forEach((item) => {
        if (item.plbQuantity < item.quantity) {
          confirmText.push(item.pTitle + ': 库存剩余' + item.plbQuantity)
        }
      })
      if (confirmText.length > 0) {
        const newDatas = []
        const h = this.$createElement
        for (const i in confirmText) {
          newDatas.push(h('p', null, confirmText[i]))
        }
        this.$alert('产品库存不足', {
          title: '产品库存不足',
          message: h('div', null, newDatas),
          showCancelButton: false,
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {})
        return true
      } else {
        return false
      }
    },
    getQueryProductList() {
      const params = {
        SkipCount: this.currentPage,
        MaxResultCount: this.pageSize
      }
      if (this.queryModel.length > 0) {
        params.PTitle = this.queryModel
      }
      if (this.QCategoryNo.length > 0) {
        params.QCategoryNo = this.QCategoryNo
      }
      getQueryProductList(params)
        .then((res) => {
          if (!res.error) {
            this.list = res.items
            this.total = res.totalCount
            this.loading = false
          }
        })
        .catch((err) => {
          if (err.response.data.error.message == '商品信息为空') {
            this.list = []
            // if (this.checkName.length > 0) {
            //   if (this.queryModel.length > 0) {
            //     this.$message.error('{ ' + this.checkName + ' }下不存在{ ' + this.queryModel + ' }商品')
            //   } else {
            //     this.$message.error(this.checkName + '下无可购买商品')
            //   }
            // } else if (this.queryModel.length > 0) {
            //   this.$message.error('不存在{ ' + this.queryModel + '} 的商品')
            // }
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.orderRecordCmpt {
  padding: 10px;

  .form-baseinfo {
    height: 780px;
    padding: 10px;

    .productCardList {
      max-height: 640px;
      flex-shrink: 0;
      overflow-y: auto;

      .productCard {
        padding-left: 5px;
        padding-right: 5px;
        padding-bottom: 10px;

        .cardLeft {
          width: 100px;
          height: 120px;
        }

        .cardButton {
          margin-top: 3px;
          margin-bottom: 3px;
          width: 270px;
          word-wrap: break-word;
          overflow-wrap: break-word;
          white-space: normal;
          height: auto;
          overflow: hidden;
        }

        .image {
          border: 1px solid #dcdfe6;
          width: 100px;
          height: 100px;
        }
      }
    }

    .clearfix {
      // height: 10px;
      span {
        font-size: 15px;
      }
    }

    .box-card {
      height: 650px;
      max-height: 650px;
      margin-left: 10px;

      .shoppingCard {
        flex-shrink: 0;
        overflow-y: auto;
        max-height: 450px;

        ::v-deep .el-divider {
          margin: 10px 0;
        }

        .shopping_specs {
          height: 30px;
          margin-left: 40%;

          .shopping_Tnum {
            line-height: 30px;
            height: 30px;
          }

          .shopping_number {
            // width: 100%;
            line-height: 30px;
            height: 30px;
          }
        }

        .shopping_danger {
          // width: 100%;
          line-height: 30px;
          height: 30px;
        }

        .shopping_Title {
          margin-left: 20px;
          // width: 100%;
          line-height: 30px;
          height: 30px;
          font-size: 14px;
        }
      }
    }

    ::v-deep .el-tree-node__content {
      border: 1px solid #dcdfe6;
      height: 40px;
    }
  }

  .settleDialog {
    margin-top: 30px;

    .settleSuserCardNo {
      ::v-deep .el-form-item__label {
        line-height: 40px;
      }
    }

    ::v-deep .el-form-item__content {
      width: 160px;
    }

    ::v-deep .el-form-item {
      margin-bottom: 1px;
    }

    span {
      font-size: 16px;
    }
  }
}

.noMore {
  line-height: 20px;
  /*垂直居中关键*/
  text-align: center;
  height: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 2px;
}

::v-deep .el-form-item__label {
  line-height: 17px;
  padding: 0;
}

::v-deep .el-form-item__content {
  width: 300px;
  line-height: 17px;
  margin-left: 50px;
}

// .btn_area {
//   padding-left: 0.1rem;
//   padding-bottom: 0.1rem;
// }
</style>
